package sort

import (
	"reflect"
	"sort"
)

//非稳定排序
func Sort(slice interface{},less func(i, j int) bool) {
	sv := reflect.ValueOf(slice)
	if sv.Kind() != reflect.Slice {
		return
	}
	s := sorter{
		slice: slice,
		lessFunc: less,
	}
	sort.Sort(s)
}

//稳定排序
func Stable(slice interface{},less func(i, j int) bool) {
	sv := reflect.ValueOf(slice)
	if sv.Kind() != reflect.Slice {
		return
	}
	s := sorter{
		slice: slice,
		lessFunc: less,
	}
	sort.Stable(s)
}

type sorter struct{
	slice 			interface{}
	lessFunc 		func(i, j int) bool
}

func (s sorter) Len() int {
	sv := reflect.ValueOf(s.slice)
	return sv.Len()
}

func (s sorter) Less(i, j int) bool {

	return s.lessFunc(i, j)
}

func (s sorter) Swap(i, j int) {
	sv := reflect.ValueOf(s.slice)
	if sv.Kind() != reflect.Slice {
		return
	}
	if i >= sv.Len() || j >= sv.Len() {
		return
	}
	temp := reflect.ValueOf(sv.Index(i).Interface())
	sv.Index(i).Set(sv.Index(j))
	sv.Index(j).Set(temp)
}
